package com.jzo2o.customer.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.api.publics.MapApi;
import com.jzo2o.common.constants.UserType;
import com.jzo2o.common.expcetions.DBException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if(CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }


    @Autowired
    private MapApi mapApi;

    /**
     * 新增地址簿
     * @param dto
     */
    @Override
    public void insertAddressBook(AddressBookUpsertReqDTO dto) {
        //是否位默认地址
        if (dto.getIsDefault() == 1) {
            AddressBook one = this.lambdaQuery()
                    .eq(AddressBook::getUserId, UserContext.currentUserId())
                    .eq(AddressBook::getIsDefault,1)
                    .one();
            if (one != null) {
                boolean update = this.lambdaUpdate().eq(AddressBook::getId, one.getId())
                        .set(AddressBook::getIsDefault, 0).update();
            }
        }
        //获取该位置的经纬度
        String location = mapApi.getLocationByAddress(dto.getAddress()).getLocation();
        String[] split = location.split(",");
        AddressBook addressBook = BeanUtils.copyBean(dto, AddressBook.class);
        addressBook.setLon(Double.valueOf(split[0]));
        addressBook.setLat(Double.valueOf(split[1]));
        addressBook.setUserId(UserContext.currentUserId());
        this.save(addressBook);
    }


    /**
     * 地址簿查询
     * @param dto
     * @return
     */
    @Override
    public PageResult<AddressBookResDTO> getAddressBook(AddressBookPageQueryReqDTO dto) {

        Page<AddressBook> addressBookPage = PageUtils.parsePageQuery(dto, AddressBook.class);
        Page<AddressBook> bookIPage = this.lambdaQuery()
                .eq(AddressBook::getUserId, UserContext.currentUserId())
                .eq(AddressBook::getIsDeleted,UserType.SYSTEM)
                .orderBy(!dto.getIsAsc1(), dto.getIsAsc1(), AddressBook::getIsDefault)
                .orderBy(!dto.getIsAsc1(), dto.getIsAsc2(), AddressBook::getUpdateTime)
                .page(addressBookPage);
        return  PageUtils.toPage(bookIPage,AddressBookResDTO.class);
    }


    /**
     * 根据id查询地址簿
     * @param id
     * @return
     */
    @Override
    public AddressBookResDTO getByIdAddress(Long id) {
        AddressBook addressBook = this.lambdaQuery()
                .eq(AddressBook::getId, id)
                .eq(AddressBook::getIsDeleted, UserType.SYSTEM)
                .one();
        if (ObjectUtils.isEmpty(addressBook)) {
            throw new ForbiddenOperationException("地址簿不存在");
        }
        return BeanUtils.copyBean(addressBook, AddressBookResDTO.class);
    }


    /**
     * 修改地址簿
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateAddressBook(Long id,AddressBookUpsertReqDTO dto) {
        //判断地址簿是否存在
        AddressBook addressBook = this.lambdaQuery()
                .eq(AddressBook::getId, id)
                .eq(AddressBook::getIsDeleted,UserType.SYSTEM)
                .one();
        if (addressBook == null){
            throw new ForbiddenOperationException("地址簿不存在");
        }
        //先判断是否修改为了默认地址
        if (dto.getIsDefault() == 1) {
            AddressBook one = this.lambdaQuery()
                    .eq(AddressBook::getCreateBy,UserContext.currentUserId())
                    .eq(AddressBook::getIsDefault,1)
                    .one();
            if (one != null) {
                boolean update = this.lambdaUpdate()
                        .eq(AddressBook::getId, one.getId())
                        .set(AddressBook::getIsDefault, 0).update();
            }
        }
        //封经纬度
        AddressBook book = BeanUtils.copyBean(dto, AddressBook.class);
        String location = mapApi.getLocationByAddress(dto.getAddress()).getLocation();
        String[] split = location.split(",");
        book.setLon(Double.valueOf(split[0]));
        book.setLat(Double.valueOf(split[1]));
        boolean result = this.lambdaUpdate().eq(AddressBook::getId, id)
                .update(book);
        if (!result){
            throw new DBException("修改失败");
        }
    }


    /**
     * 批量删除地址簿
     * @param ids
     */
    @Override
    public void batchDeleteAddressBook(List<String> ids) {
        for (String id : ids) {
            //批量删除不是从数据库中删除，是将逻辑删除
            //判断当前的数据是否存在
            AddressBook addressBook = this.lambdaQuery()
                    .eq(AddressBook::getId, id)
                    .eq(AddressBook::getIsDeleted,UserType.SYSTEM)
                    .one();
            if (addressBook == null){
                throw new ForbiddenOperationException("地址簿不存在");
            }
            boolean result = this.lambdaUpdate().eq(AddressBook::getId, id)
                    .set(AddressBook::getIsDeleted, UserType.C_USER)
                    .update();
            if (!result){
                throw new DBException("删除失败");
            }
        }
    }

    /**
     * 设置/取消默认地址
     * @param id
     * @param flag
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setDefaultAddressBook(Long id, Integer flag) {
        //判断地址簿是否存在
        AddressBook addressBook = this.lambdaQuery()
                .eq(AddressBook::getId, id)
                .eq(AddressBook::getIsDeleted, UserType.SYSTEM)
                .one();
        if (addressBook == null) {
            throw new ForbiddenOperationException("地址簿不存在");
        }
        //等于1就是设置默认地址
        if (flag == 1) {
            //查询他是否含有默认地址，如果有默认地址，就更改掉
            AddressBook book = this.lambdaQuery()
                    .eq(AddressBook::getUserId, UserContext.currentUserId())
                    .ne(AddressBook::getId, id)
                    .eq(AddressBook::getIsDefault, UserType.C_USER)
                    .eq(AddressBook::getIsDeleted, UserType.SYSTEM)
                    .one();
            if (book != null) {
                boolean update = this.lambdaUpdate()
                        .eq(AddressBook::getId, book.getId())
                        .set(AddressBook::getIsDefault, 0).update();
            }
        }
        //更改当前地址簿的信息
        boolean result = this.lambdaUpdate()
                .eq(AddressBook::getId, id)
                .set(AddressBook::getIsDefault, flag)
                .update();
        if (!result) {
            throw new DBException("设置默认地址失败");
        }
    }


    /**
     * 获取默认地址
     * @return
     */
    @Override
    public AddressBookResDTO getDefultAddress() {
        //判断当前用户是否有默认地址
        AddressBook addressBook = this.lambdaQuery()
                .eq(AddressBook::getUserId, UserContext.currentUserId())
                .eq(AddressBook::getIsDefault, UserType.C_USER).one();
        if (addressBook == null){
            return null;
        }
        return BeanUtils.copyBean(addressBook, AddressBookResDTO.class);
    }
}
